import json
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.clickjacking import xframe_options_exempt
from .models import LogsDB


@csrf_exempt
def log_add(request):
    if request.method == "POST":
        json_result = json.loads(request.body.decode("utf-8"))
        print("# " * 10, json_result, "# " * 10, sep='\n')
        try:
            LogsDB.objects.create(
                app_name=json_result["app_name"],
                deploy_version=json_result["deploy_version"],
                env_name=json_result["env_name"],
                ip_address=json_result["ip_address"],
                log_content=json_result["log_content"],
                operation_no=json_result["operation_no"],
                operation_type=json_result["operation_type"],
                user_name=json_result["user_name"]
            )
            return JsonResponse({"msg": "ok"})
        except Exception as e:
            print("Write automan log error : " + str(e))
            return JsonResponse({"msg": "failed"})
    else:
        print("Only POST method is valid")
        return JsonResponse({"msg": "failed"})


@xframe_options_exempt    # 不进行跨域检查
def log_show(request):
    deploy_version = request.GET.get("deploy_version")
    app_name = request.GET.get("app_name")
    env_name = request.GET.get("env_name")
    operation_no = request.GET.get("operation_no")

    context = {
        "deploy_version": deploy_version,
        "app_name": app_name,
        "env_name": env_name,
        "operation_no": operation_no
    }

    return render(request, "wslog/websocket.html", context)
